interface ChatHistoryItem {
  id: string;
  title: string;
}

interface Message {
  role: string;
  content: string;
  timestamp: Date;
}

const BASE_URL: string = 'http://localhost:8080';

export const chatAPI = {
  // 发送聊天消息（支持 FormData 和字符串）
  async sendMessage(data: FormData | string, chatId?: string): Promise<ReadableStreamReader<Uint8Array>> {
    try {
      const url = new URL(`${BASE_URL}/ai/chat`);
      if (chatId) {
        url.searchParams.append('chatId', chatId);
      }

      const response = await fetch(url, {
        method: 'POST',
        body: data instanceof FormData ? data : new URLSearchParams({ prompt: data })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      if (!response.body) {
        throw new Error('Response body is null');
      }

      return response.body.getReader();
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  },

  // 获取分类聊天历史（支持 chat/pdf/service 类型）
  async getChatHistory(type: 'chat' | 'pdf' | 'service' = 'chat'): Promise<ChatHistoryItem[]> {
    try {
      const response = await fetch(`${BASE_URL}/ai/history/${type}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const chatIds: string[] = await response.json();

      return chatIds.map(id => ({
        id,
        title: type === 'pdf' ? `PDF对话 ${id.slice(-6)}` :
          type === 'service' ? `咨询 ${id.slice(-6)}` :
            `对话 ${id.slice(-6)}`
      }));
    } catch (error) {
      console.error('API Error:', error);
      return [];
    }
  },

  // 获取特定对话消息记录
  async getChatMessages(chatId: string, type: 'chat' | 'pdf' | 'service' = 'chat'): Promise<Message[]> {
    try {
      const response = await fetch(`${BASE_URL}/ai/history/${type}/${chatId}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const messages: Omit<Message, 'timestamp'>[] = await response.json();

      return messages.map(msg => ({
        ...msg,
        timestamp: new Date() // 实际应根据后端返回时间戳修改
      }));
    } catch (error) {
      console.error('API Error:', error);
      return [];
    }
  },

  // 通用流式请求方法（供多个功能复用）
  // 修改后
  async streamedRequest(url: string): Promise<ReadableStreamReader<Uint8Array>> {
    try {
      const response = await fetch(url);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      if (!response.body) {
        throw new Error('Response body is null');
      }

      return response.body.getReader();
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  },

  // 游戏消息接口
  async sendGameMessage(prompt: string, chatId: string): Promise<ReadableStreamReader<Uint8Array>> {
    const encodedPrompt = encodeURIComponent(prompt);
    return this.streamedRequest(
      `${BASE_URL}/ai/game?prompt=${encodedPrompt}&chatId=${chatId}`
    );
  },

  // 客服消息接口
  async sendServiceMessage(prompt: string, chatId: string): Promise<ReadableStreamReader<Uint8Array>> {
    const encodedPrompt = encodeURIComponent(prompt);
    return this.streamedRequest(
      `${BASE_URL}/ai/service?prompt=${encodedPrompt}&chatId=${chatId}`
    );
  },

  // PDF 问答接口
  async sendPdfMessage(prompt: string, chatId: string): Promise<ReadableStreamReader<Uint8Array>> {
    const encodedPrompt = encodeURIComponent(prompt);
    try {
      const response = await fetch(
        `${BASE_URL}/ai/pdf/chat?prompt=${encodedPrompt}&chatId=${chatId}`,
        {
          method: 'GET',
          signal: AbortSignal.timeout(30000)
        }
      );

      if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
      }

      if (!response.body) {
        throw new Error('Response body is null');
      }

      return response.body.getReader();
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  }
};
